package com.hwbsite.hwbback.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hwbsite.hwbback.config.MinioTemplate;
import com.hwbsite.hwbback.consstants.CommonConstants;
import com.hwbsite.hwbback.entity.FileInfo;
import com.hwbsite.hwbback.entity.UploaderRES;
import com.hwbsite.hwbback.mapper.FileInfoMapper;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.file.Files;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
@Component
public class FileUploader {

    @Autowired
    private  MinioTemplate minioTemplate;

    @Value("${spring.profiles.active}")
    private String profile;

    @Resource
    private   FileInfoMapper fileInfoMapper;


    private String path;



    public List<UploaderRES> uploade(MultipartFile file, String path, boolean thumbnail,  Integer order) throws Exception {

        this.path = "dev".equals(this.profile) ? CommonConstants.DEV_WB_IMG_PATH +  LocalDateTime.now().format(DateTimeFormatter.BASIC_ISO_DATE) +  "/" : path;

        List<UploaderRES> res = new ArrayList<>();

        String fileName = StrUtil.isBlank(file.getOriginalFilename()) ? CreateIdUtil.createId("P") + ".png" : CreateIdUtil.createId("P") + file.getOriginalFilename();

        res.add(this.saveFile(file.getInputStream(), false, order, fileName));

        if (thumbnail){

            String id = CreateIdUtil.createId("P");
            File tempFile = File.createTempFile(id , ".png");

            Thumbnails.of(file.getInputStream()).scale(0.2).toOutputStream(new FileOutputStream(tempFile));

            res.add(this.saveFile(new FileInputStream(tempFile), thumbnail, order , id + ".png"));
            tempFile.delete();
        }


        return res;
    }

    public List<UploaderRES> uploade(MultipartFile[] files, String path, boolean thumbnail) throws Exception {

       List<UploaderRES> res = new ArrayList<>();

        for (int i =0 ; i < files.length ; i++){
            res.addAll(this.uploade(files[i] ,path, thumbnail, i));
        }

        return res;
    }

    private UploaderRES saveFile(InputStream ins, boolean isThumbnail , Integer i , String fileOName) throws Exception {

        byte[] fileTmp = IoUtil.readBytes(ins, false);

        String md5 = DigestUtils.md5Hex(fileTmp);


        FileInfo fileInfo = fileInfoMapper.selectOne(Wrappers.<FileInfo>lambdaQuery().eq(FileInfo::getFileMd5, md5));
        String id = UUID.randomUUID().toString();

        if (fileInfo == null){

            String[] filePath =  this.path.split("-", 2);
            String bucket = filePath[0];
            String fileName = filePath[1].concat(fileOName);
            minioTemplate.fileUploader(bucket, fileName, IoUtil.toStream(fileTmp));


            fileInfo = new FileInfo();
            fileInfo.setFileId(id);
            fileInfo.setFilePath(this.path);
            fileInfo.setFileName(fileOName);
            fileInfo.setUserId(UserTokenUtils.getUser().getUserId());
            fileInfo.setFileMd5(md5);
            fileInfoMapper.insert(fileInfo);
        }else {
            id = fileInfo.getFileId();
            fileOName = fileInfo.getFileName();
        }

        UploaderRES res = new UploaderRES();
        res.setId(id);
        res.setThumbnail(isThumbnail);
        res.setOrderNo(i);
        res.setFileName(fileOName);
        return res;
    }

    public String uploadAvatar (String base64){
        this.path = "avatar-" + UserTokenUtils.getUser().getUsername()  +  "/";

        base64 = base64.split(";base64,")[1];

        String id = CreateIdUtil.createId("P");
        String idT = CreateIdUtil.createId("P");
        File tempFile = null;
        File tempThum = null;
        String fileName = null;
        try {
            tempFile = File.createTempFile(id , ".png");
            tempThum = File.createTempFile(idT , ".png");
            Base64.decodeToFile(base64, tempFile);
            long size = tempFile.length() / 1024 ;
            double scale = 1;
            if(size > 500){
                scale = new BigDecimal(500).divide(new BigDecimal(size), 1, RoundingMode.HALF_UP).doubleValue();
                Thumbnails.of(Files.newInputStream(tempFile.toPath())).scale(scale).toOutputStream(Files.newOutputStream(tempThum.toPath()));
                fileName = saveFile(Files.newInputStream(tempThum.toPath()), false, 1 , tempThum.getName()).getFileName();
            }else {
                fileName = saveFile(Files.newInputStream(tempFile.toPath()), false, 1 , tempFile.getName()).getFileName();
            }

            return "/tt/common/no/getFile?path=" + this.path + fileName ;

        } catch (Exception e) {
            log.error("上传头像失败",e);
        }finally {
            tempFile.delete();
            tempThum.delete();
        }
        return null;
    }
}
